/*
 * @Author: eycode
 * @Date: 2021-05-21 11:05:25
 * @LastEditTime: 2021-05-21 11:49:34
 * @LastEditors: eycode
 * @Description: 摇杆父节点
 * @Other: 
 */

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
    /**摇杆背景节点：rocker_bg */
    @property(cc.Node)
    rocker: cc.Node = null;

    /**摇杆节点：stick */
    @property(cc.Node)
    stick: cc.Node = null;

    /**圆的半径 */
    private _radius: number = 0;

    /**人物移动的向量（具有大小和方向） */
    public dir: cc.Vec2 = cc.v2();

    /**摇杆所在位置 */
    private _startPosition: cc.Vec2 = cc.v2();

    start() {
        this.node.opacity = 0;
        this.dir = cc.v2(0, 0);
        this._radius = this.rocker.width / 2;
        this.node.on(cc.Node.EventType.TOUCH_START, this._onStart.bind(this));
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onMove.bind(this));
        this.node.on(cc.Node.EventType.TOUCH_END, this._onEnd.bind(this));
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onEnd.bind(this));
    }

    /**
     * @description: 触摸开始
     * @param {*} event
     * @return {*}
     */
    private _onStart(event) {
        //将世界坐标转化为父节点的相对坐标
        const touchPos = this.node.convertToNodeSpaceAR(event.getLocation());
        this.node.opacity = 255;
        this._startPosition = touchPos;
        this.rocker.setPosition(touchPos);
        this.stick.setPosition(touchPos);
    }

    /**
     * @description: 触摸移动
     * @param {*} event
     * @return {*}
     */
    private _onMove(event) {
        const pos = this.rocker.convertToNodeSpaceAR(event.getLocation());
        const distance = pos.mag();
        const posX = this._startPosition.x + pos.x;
        const posY = this._startPosition.y + pos.y;
        this.dir = cc.v2(posX, posY).sub(this.rocker.getPosition()).normalize();
        if (distance > this._radius) {
            const x = this._startPosition.x + this._radius * pos.x / distance;
            const y = this._startPosition.y + this._radius * pos.y / distance;
            this.stick.setPosition(cc.v2(x, y));
        } else {
            this.stick.setPosition(cc.v2(posX, posY));
        }
    }

    /**
     * @description: 触摸结束
     * @param {*} event
     * @return {*}
     */
    private _onEnd(event) {
        this.node.opacity = 0;
    }
}
